﻿<?php
class TGate1C{
  private $url_pattern;
  private $user_info;
  private $error;
  private $errornum;
  private $response;

  function TGate1C($host, $port, $username = 'WebUser', $password = ''){
    $url = "http://$host";
    if(!empty($port)) $url .= ":$port";
    $url .= '/gate1C_v1/rest/TGate1C/%22';
    $this->url_pattern = $url;

    $user_info = $username;
    if(empty($user_info)) $user_info = 'none';
    if(!empty($password)) $user_info .= ":$password";
    $this->user_info = $user_info;

  }

  private function build_url($method){
    return $this->url_pattern."$method%22";
  }

  private function execute_method($method, $params){
    $this->error = '';
    $this->response = null;
    $ok = false;
    $ch = curl_init($this->build_url($method));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: text/xml charset=utf-8'));
    if(!empty($this->user_info)) curl_setopt($ch, CURLOPT_USERPWD, $this->user_info);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    $response = curl_exec($ch);
    $this->errornum = curl_errno($ch);
    if($this->errornum)
      $this->error = curl_error($ch);
    else {
      $response = json_decode($response);
      if(property_exists($response, 'error')){
	$this->errornum = 500;
        $this->error = $response->error;
      } else {
        $response = $response->result[0];
        if(is_null($response)){
          $this->errornum = 504;
          $this->error = 'Сервис недоступен. Возможно неверные данные авторизации, либо критическая ошибка на сервере.';          
        } else if(property_exists($response, 'error')){
          $this->errornum = 500;
          $this->error = $response->error;
        } else {
          $this->response = $response;
          $ok = true;
        }
      }
    }
    curl_close($ch);
    return $ok;
  }

  function get_errornum(){
    return $this->errornum;
  }

  function get_error() {
    return $this->error;
  }

  function get_response() {
    return $this->response;
  }

  function WebExec1CModule($db_alias, $module_path, $params){
    $method_params = array($db_alias, $module_path, $params);
    return $this->execute_method('WebExec1CModulePHP', $method_params);
  }
}
?>